package com.onpositive.knowledge.model;

import java.util.HashSet;
import java.util.Set;

import com.onpositive.semantic.model.api.realm.IRealm;
import com.onpositive.semantic.model.api.realm.Realm;

public class ThingFilter {
	

	public static IRealm<IThing> filter( IRealm<IThing> sourceRealm , IThing root )
	{
		if( root == null )
			return sourceRealm ;
		
		HashSet<IThing> rightDocs = new HashSet<IThing>() ;
		rightDocs.add(root) ;
		
		HashSet<IThing> wrongDocs = new HashSet<IThing>() ;

		for( IThing pd : sourceRealm )
			checkMembership( pd, root, rightDocs, wrongDocs ) ;
		
		return new Realm<IThing>( rightDocs ) ;
				
	}
	
	private static boolean checkMembership( IThing doc, IThing root , Set<IThing> right, Set<IThing> wrong )
	{
		if( right.contains( doc ) )
			return true ;
		
		if( wrong.contains( doc ) )
			return false ;
		
		//remember that roots of the parsed category have empty set of parents 
		for( IType parent : doc.getTypes() )
		{
			if( !(parent instanceof IThing ) )
				continue ;

			if( checkMembership( (IThing)parent, root, right, wrong) )
			{
				right.add( doc ) ;
				return true ;
			}
		}
		
		wrong.add( doc ) ;
		return false ;
		
	}
}
